package com.yihukurama.sysbase.sysservice.impl;

import com.yihukurama.base.app.constant.Constant;
import com.yihukurama.base.app.exception.TipsException;
import com.yihukurama.base.app.utils.EmptyUtil;
import com.yihukurama.base.app.utils.ruoyi.ScheduleUtils;
import com.yihukurama.sysbase.framework.domainservice.JobService;
import com.yihukurama.sysbase.framework.entity.JobEntity;
import com.yihukurama.sysbase.sysservice.IQuartz;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class QuartzService implements IQuartz {

    @Autowired
    private Scheduler scheduler;

    @Autowired
    JobService jobService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean runJob(JobEntity job) throws SchedulerException {
        boolean result = false;
        String jobId = job.getId();
        if (EmptyUtil.isEmpty(jobId)){
            return false;
        }
        String jobGroup = job.getJobGroup();
        JobEntity properties = null;
        try {
            properties = jobService.load(job);
        } catch (TipsException e) {
            throw new RuntimeException(e);
        }
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(Constant.TASK_PROPERTIES, properties);
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey))
        {
            result = true;
            scheduler.triggerJob(jobKey, dataMap);
        }
        return result;
    }
}
